package com.wingsfrog.travel.controller;

import com.wingsfrog.travel.controller.dto.request.LoginReqDto;
import com.wingsfrog.travel.modules.entity.User;
import com.wingsfrog.travel.service.UserService;
import com.wingsfrog.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Created by rankin on 16/3/29.
 */
@Controller
@RequestMapping(value = "users")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping(method = {RequestMethod.GET})
    @ResponseBody
    public Object getUsers() throws Exception {
        throw new Exception("dd");
    }

    /**
     * @api {post} /users/login 用户登录
     * @apiParam {String} phone 用户电话号码
     * @apiParam {String} code 验证码
     * @apiSuccess {String} token 登录成功返回一个用户登录的token
     */
    @RequestMapping(value = "login", method = {RequestMethod.POST})
    @ResponseBody
    public Object login(@RequestBody LoginReqDto reqDto) throws Exception {
        //todo 微信登录
        if (!Objects.equals(reqDto.getCode(), "0000")) throw new Exception("validate error");

        User u = userService.findUserByPhone(reqDto.getPhone());
        Timestamp now = new Timestamp(System.currentTimeMillis());
        String token;
        if (u == null) {
            u = new User();
            u.setPhone(reqDto.getPhone());
            u.setCreatedAt(now);
            u.setUpdatedAt(now);
            u.setLastLoginDate(now);
            u.setIsDeleted(false);
            u.setSex((byte) 0);
            u.setToken(token = RandomUtil.generateToken(16));
            userService.saveUser(u);
        } else {
            token = u.getToken();
            if (token == null) {
                token = RandomUtil.generateToken(16);
                u.setUpdatedAt(now);
                u.setLastLoginDate(now);
                u.setToken(token);
                userService.saveUser(u);
            }
        }

        Map<String, String> tokenResponse = new HashMap<String, String>();
        tokenResponse.put("token", token);
        return tokenResponse;
    }
}
